package
{
	import flash.display.Sprite;
	import flash.geom.Point;

	public class Bot
	{
		public var speed:Number = 50; // Units Per Second
		public var parentDisplay:Sprite;
		public var display:Sprite;
		public var currentPosition:Point;
		
		private var m_pathFinder:PathFinder;
		private var m_waypointReached:Boolean;
		private var m_distanceToTravel:Number;
		private var m_nextWaypoint:Point;
		private var m_nextPosition:Point;
		private var m_finalDestination:Point;
		private var m_finalDestinationReached:Boolean;
		public var world:World;
		public var vision:Number = 5;
		public function Bot()
		{
			m_waypointReached = true;
			m_finalDestinationReached = true;
		}
		
		public function initialize():void{
			m_nextPosition = currentPosition;
			display = Util.getCircle(0xff0000, 2);
			m_pathFinder = new PathFinder(world);
			parentDisplay.addChild(display);
			
			if(PathFinder.ENABLE_VISIUALIZATION){
				parentDisplay.addChild(m_pathFinder.display);
			}			
		}
		
		public function moveTo(finalDestination:Point):void{
			m_finalDestination = finalDestination;
			m_pathFinder.setup(m_finalDestination, vision);
			m_nextWaypoint = m_pathFinder.getNextWaypoint(currentPosition); // calling this here might be logically redundant
			m_finalDestinationReached = false;
			moveToWaypoint(m_nextWaypoint);
		}
		
		private function moveToWaypoint(waypoint:Point):void{
			m_nextWaypoint = waypoint;
			m_distanceToTravel = m_nextWaypoint.subtract(currentPosition).length;
			m_waypointReached = false;
		}
		
		public var hasMoved:Boolean = false;
		
		public function update():void{
			var distanceFactor:Number;
			if(!hasMoved){
				moveTo(new Point(Global.WORLD_RECT.width, Global.WORLD_RECT.height));
				hasMoved = true;
			}
			

			if(!m_finalDestinationReached){
				if(m_distanceToTravel <= 0){
					m_waypointReached = true;
					currentPosition = m_nextPosition = m_nextWaypoint;	
					if(m_nextPosition.subtract(m_finalDestination).length < 2){
						m_finalDestinationReached = true;	
					}
					
					m_nextWaypoint = m_pathFinder.getNextWaypoint(m_nextWaypoint);
					moveToWaypoint(m_nextWaypoint)
				}
				
				currentPosition = m_nextPosition;
				distanceFactor = speed * Global.DELTA_TIME / 1000;
				var delta:Point = Util.getNormalizedDistance(currentPosition, m_nextWaypoint, distanceFactor);
				m_distanceToTravel -= distanceFactor;
				m_nextPosition = currentPosition.add(delta);
				updateDisplay();
			}
		}
		
		private function updateDisplay():void{
			display.x = currentPosition.x * Global.PPU + Global.PPU/2;
			display.y = currentPosition.y * Global.PPU + Global.PPU/2;
		}
	}
}